from django.shortcuts import render, redirect
from bug_manage.forms.project import ProjectModelForm
from django.http import JsonResponse, HttpResponse
from django.conf import settings
import time
from bug_manage import models
from utils.tencent.cos import create_bucket


def project_list(request):
    """项目管理"""
    if request.method == 'GET':
        """GET请求获取项目列表展示"""
        project_dict = {'star': [], 'my': [], 'join': []}  # star星标项目，my我创建的项目，join我参与的项目
        my_project_list = models.Project.objects.filter(creator=request.tracer.user)
        for row in my_project_list:
            if row.star:
                project_dict['star'].append({"value":row,'type':'my'})
            else:
                project_dict['my'].append(row)
        join_project_list = models.ProjectUser.objects.filter(user=request.tracer.user)
        for item in join_project_list:
            if item.star:
                project_dict['star'].append({"value":item.project,'type':'my'})
            else:
                project_dict['join'].append(item.project)
        # print(project_dict)
        # for item in project_dict['my']:
        #     print(item.name)
        form = ProjectModelForm(request)
        return render(request, 'project_list.html', {'form': form, 'project_dict': project_dict})
    """post请求创建项目"""
    form = ProjectModelForm(request, data=request.POST)
    if form.is_valid():
        #1.为项目创建一个腾讯对象存储:名称为手机号+时间戳
        name = form.cleaned_data.get('name')
        bucket = "{}-{}-{}-1306602357".format(name, request.tracer.user.mobile_phone, str(int(time.time())))
        region = settings.TENCENT_COS_REGION
        create_bucket(bucket, region)
        #2.把桶和区域写入数据库
        form.instance.bucket = bucket
        form.instance.region = region
        # 验证通过,创建项目表单 + 创建者
        form.instance.creator = request.tracer.user
        instance = form.save()
        # 3.初始化问题类型
        issues_type_object_list = []
        for item in models.IssuesType.PROJECT_INIT_LIST:
            issues_type_object_list.append(models.IssuesType(project=instance,title=item))
        models.IssuesType.objects.bulk_create(issues_type_object_list)

        return JsonResponse({'status': True})
    return JsonResponse({'status': False, 'error': form.errors})


def project_star(request, project_type, project_id):
    """"星标项目"""
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=True)
        return redirect('project_list')
    elif project_type == "join":
        models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=True)
        return redirect('project_list')
    else:
        return HttpResponse('请求错误')

def project_unstar(request, project_type, project_id):
    """"取消星标项目"""
    if project_type == 'my':
        models.Project.objects.filter(id=project_id, creator=request.tracer.user).update(star=False)
        return redirect('project_list')
    elif project_type == "join":
        models.ProjectUser.objects.filter(project_id=project_id, user=request.tracer.user).update(star=False)
        return redirect('project_list')
    else:
        return HttpResponse('请求错误')
